import Home from '../../components/Fragments/home';
import Chat from '../../components/Fragments/chat';
import History from '../../components/Fragments/history';
import FooterNav from '../../components/FooterNav';
import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { IP_NAME } from '../../configProvider/namespace';
const Index = () => {
  const [fragmentId, setFragmentId] = useState(0);

  const changeFragment = (index: number) => {
    setFragmentId(index);
  }
  useEffect(() => {
    Taro.getStorage({
      key: 'token',
      fail: () => {
        Taro.reLaunch({ url: '../login/index' })
      }
    })
    interval()
  }, [])
  const interval = () => {
    console.log('checking if conversation ending...');
    Taro.getStorage({
      key: 'chatId',
      success: function (res) {
        if (!res.data) {
          return;
        }
        console.log(res.data)
        let chatid = res.data;
        Taro.request({
          url: `${IP_NAME}/conversation/isEnd?id=${res.data}`,
          data: {},
          header: {
            'content-type': 'application/json'
          },
          success: function (res) {
            console.log(res.data)
            if (res.data.data) {//true，结束
              Taro.setStorage({
                key: 'chatId',
                data: ''
              })
              Taro.setStorage({
                key: 'conversationID',
                data: ''
              })

              Taro.showModal({
                title: '提示',
                content: '咨询会话已结束，请前往评分',
                success: function (res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                    Taro.navigateTo({ url: `../submitComment/index?chatid=${chatid}` })
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                    Taro.getStorage({
                      key: 'groupID',
                      success: (res) => {
                        console.log('delete group', res.data)
                        Taro.request({
                          url: `${IP_NAME}/im/group/delete?group_id=${res.data}`,
                          data: {},
                          header: {
                            'content-type': 'application/json'
                          },
                          success: function (res) {
                            console.log(res.data)
                          }
                        })
                      }
                    })
                    Taro.reLaunch({ url: '../index/index' })
                  }
                }
              })
            }
          }
        })
      }
    })
    setTimeout(() => {
      interval()
    }, 5000)
  }
  return <>
    {[<Home />, <Chat />, <History />][fragmentId]}
    <FooterNav defaultIndex={0} onChangeIndex={changeFragment} />
  </>
}

export default Index;
